package com.travel.service.impl.Post;

import com.github.pagehelper.PageHelper;
import com.travel.exception.ResourceNotFoundException;
import com.travel.exception.UnauthorizedException;
import com.travel.mapper.content.CommentMapper;
import com.travel.mapper.content.PostMapper;
import com.travel.mapper.user.UserMapper;
import com.travel.model.dto.comment.CommentRequest;
import com.travel.model.dto.comment.RatingStats;
import com.travel.model.dto.post.PostDTO;
import com.travel.model.dto.user.SimpleUserDTO;
import com.travel.model.entity.auth.User;
import com.travel.model.entity.content.Comment;
import com.travel.model.entity.content.Post;
import com.travel.service.Service.PostService;
import com.travel.service.Service.UserService;
import com.travel.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
//文章服务实现类 获取所有文章 获取特定城市文章 获取特定文章 创建文章 更新文章 删除文章 搜索文章 添加评论 获取评论 获取评分统计
@Service
@RequiredArgsConstructor
public class PostServiceImpl implements PostService {

    private final PostMapper postMapper;
    private final UserService userService;
    private final CommentMapper commentMapper;
    private final UserMapper userMapper;

    @Override
    public Page<Post> getAllPosts(Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Post> posts = postMapper.findAll();
        return new PageImpl<>(posts);
    }

    @Override
    public Page<Post> getPostsByCity(String city, String category, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Post> posts;
        if (category != null && !category.isEmpty()) {
            posts = postMapper.findByCityAndCategory(city, category);
        } else {
            posts = postMapper.findByCity(city);
        }
        return new PageImpl<>(posts);
    }

    @Override
    @Transactional
    public PostDTO createPost(PostDTO postDTO) {
        Post post = new Post();
        BeanUtils.copyProperties(postDTO, post);
        
        if (ObjectUtils.isEmpty(post.getCoverImage())) {
            post.setCoverImage("http://pic.maxtral.fun/Onedrive/2024/12/18/default-post-cover.jpg");
        }
        
        Long userId = SecurityUtils.getCurrentUserId();
        post.setUserId(userId);
        
        post.setStatus(1);
        post.setCreatedTime(LocalDateTime.now());
        post.setViewCount(0);
        
        User currentUser = userMapper.findById(userId)
            .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
        post.setUser(currentUser);
        
        postMapper.insert(post);
        return convertToDTO(post);
    }

    @Override
    @Transactional
    public PostDTO updatePost(Long id, PostDTO postDTO) {
        Post post = postMapper.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("文章不存在"));
            
        BeanUtils.copyProperties(postDTO, post, "id", "userId", "createdTime", "status");
        post.setUpdatedTime(LocalDateTime.now());
        
        postMapper.update(post);
        return convertToDTO(post);
    }

    @Override
    @Transactional
    public void deletePost(Long id) {
        Post post = postMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Post not found with id: " + id));
        postMapper.delete(post);
    }

    @Override
    public Page<Post> searchPosts(String keyword, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Post> posts = postMapper.searchPosts(keyword);
        return new PageImpl<>(posts);
    }

    @Override
    public List<Post> findHotPosts(Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        return postMapper.findHotPosts();
    }

    @Override
    public List<Post> findLatestPosts(Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        return postMapper.findLatestPosts();
    }

    @Override
    public Page<Post> getCurrentUserPosts(Pageable pageable) {
        User currentUser = userService.getCurrentUser();
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Post> posts = postMapper.findByUserId(currentUser.getId());
        return new PageImpl<>(posts);
    }

    @Override
    @Transactional
    public Comment addComment(Long postId, CommentRequest request) {
        Post post = postMapper.findById(postId)
            .orElseThrow(() -> new ResourceNotFoundException("文章不存在"));
            
        Comment comment = new Comment();
        comment.setContent(request.getContent());
        comment.setRating(request.getRating());
        comment.setUserId(SecurityUtils.getCurrentUserId());
        comment.setTargetId(postId);
        comment.setTargetType(Comment.TargetType.POST);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setStatus(1);
        
        commentMapper.insert(comment);
        return comment;
    }

    @Override
    public List<Comment> getComments(Long postId) {
        return postMapper.findPostComments(postId);
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        Comment comment = commentMapper.findById(commentId)
            .orElseThrow(() -> new ResourceNotFoundException("评论不存在"));
            
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (!comment.getUserId().equals(currentUserId)) {
            throw new UnauthorizedException("您没有权限删除此评论");
        }
        
        comment.setStatus(0);
        commentMapper.update(comment);
    }

    @Override
    public Post getPost(Long id) {
        return postMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("文章不存在"));
    }

    @Override
    @Transactional
    public void updatePostStatus(Long id, Integer status) {
        Post post = postMapper.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("文章不存在"));
        post.setStatus(status);
        post.setUpdatedTime(LocalDateTime.now());
        postMapper.update(post);
    }

    @Override
    public RatingStats getPostRating(Long postId) {
        RatingStats stats = new RatingStats();
        stats.setAverageRating(commentMapper.getAverageRating(
            postId, Comment.TargetType.POST));
        stats.setCommentCount(commentMapper.getCommentCount(
            postId, Comment.TargetType.POST));
        return stats;
    }

    @Override
    public PostDTO getPostDetail(Long id) {
        Post post = postMapper.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("文章不存在"));
            
        // 获取作者信息
        User author = userMapper.findById(post.getUserId())
            .orElse(null);
        post.setUser(author);
        
        PostDTO dto = convertToDTO(post);
        
        // 获取评分统计
        RatingStats stats = getPostRating(id);
        dto.setAverageRating(stats.getAverageRating());
        dto.setCommentCount(stats.getCommentCount());
        
        return dto;
    }
    
    private PostDTO convertToDTO(Post post) {
        if (post == null) {
            return null;
        }
        
        PostDTO dto = new PostDTO();
        BeanUtils.copyProperties(post, dto);
        
        // 转换评论列表中的用户信息为 SimpleUserDTO
        if (post.getComments() != null) {
            post.getComments().forEach(comment -> {
                if (comment.getUser() != null) {
                    SimpleUserDTO userDTO = new SimpleUserDTO();
                    userDTO.setId(comment.getUser().getId());
                    userDTO.setNickname(comment.getUser().getNickname());
                    userDTO.setAvatar(comment.getUser().getAvatar());
                    userDTO.setStatus(comment.getUser().getStatus());
                    comment.setUser(userDTO);
                }
            });
        }
        
        // 转换作者信息
        if (post.getUser() != null) {
            SimpleUserDTO userDTO = new SimpleUserDTO();
            userDTO.setId(post.getUser().getId());
            userDTO.setNickname(post.getUser().getNickname());
            userDTO.setAvatar(post.getUser().getAvatar());
            userDTO.setStatus(post.getUser().getStatus());
            dto.setUser(userDTO);
        }
        
        return dto;
    }
} 